package pers.mihao.quickstream.publish.strategy.filter.impl;

import org.springframework.stereotype.Component;
import pers.mihao.quickstream.publish.strategy.context.ChooseContext;
import pers.mihao.quickstream.publish.strategy.dto.ChooseAccount;
import pers.mihao.quickstream.publish.strategy.dto.ChooseAccountScore;
import pers.mihao.quickstream.publish.strategy.filter.AccountFilter;

import java.util.*;

/**
 * @author mihao
 * @since 2024/11/25
 */
@Component
public class PlatformAccountOneFilter implements AccountFilter {
    @Override
    public List<ChooseAccount> accountFilter(ChooseContext chooseContext,
                                             List<ChooseAccountScore> accountScores) {

        Map<String, List<ChooseAccountScore>> platformMap = new HashMap<>();
        for (ChooseAccountScore accountScore : accountScores) {
            List<ChooseAccountScore> chooseAccountScores = platformMap.
                    computeIfAbsent(accountScore.getChooseAccount().getPlatformCode(), c -> new ArrayList<>());
            chooseAccountScores.add(accountScore);
        }
        List<ChooseAccount> chooseAccounts = new ArrayList<>(platformMap.size());
        for (Map.Entry<String, List<ChooseAccountScore>> entry : platformMap.entrySet()) {
            chooseAccounts.add(ChooseAccount.builder()
                    .accountId(entry.getValue().stream()
                            .min(Comparator.comparingLong(ChooseAccountScore::getScope))
                            .map(ChooseAccountScore::getChooseAccount)
                            .map(ChooseAccount::getAccountId)
                            .orElseThrow())
                    .platformCode(entry.getKey())
                    .build());
        }
        return chooseAccounts;
    }
}
